package com.ecoolex.chinadutyfree.retailer.core.manager;

import java.time.Instant;
import java.util.Calendar;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ecoolex.chinadutyfree.retailer.core.dao.CouponClassExpireStrategyDAO;
import com.ecoolex.chinadutyfree.retailer.entity.Coupon;
import com.ecoolex.chinadutyfree.retailer.entity.CouponClassExpireStrategy;
import com.ecoolex.chinadutyfree.retailer.entity.CouponClassExpireStrategy.Column;
import com.ecoolex.chinadutyfree.retailer.enums.CouponClassExpiryStrategy;
import com.ecoolex.chinadutyfree.retailer.enums.CouponClassRelativeExpiryType;
import com.ecoolex.framework.common.util.Check;
import com.ecoolex.framework.common.util.DateUtil;

@Service
public class CouponClassExpireStrategyManager {
	
    @Autowired
    private CouponClassExpireStrategyDAO dao;
    
    public CouponClassExpireStrategy getByCouponClassId(Integer couponClassId) {
		return dao.selectByPrimaryKeyWithLogicalDelete(couponClassId, CouponClassExpireStrategy.NOT_DELETED);
	}

	public void create(CouponClassExpireStrategy record, String createUser) {
		record.setDeleted(CouponClassExpireStrategy.NOT_DELETED);
		record.setCreateUser(createUser);
		record.setCreateTime(Date.from(Instant.now()));
		record.setUpdateUser(createUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.insert(record);
	}

	public void update(CouponClassExpireStrategy record, String updateUser) {
		record.setUpdateUser(updateUser);
		record.setUpdateTime(Date.from(Instant.now()));
		dao.updateByPrimaryKeySelective(record, Column.excludes(Column.deleted, Column.createUser, Column.createTime));
	}

	/**
	 * 计算有效期
	 * 
	 * @param coupon
	 * @param record
	 */
	public void calculateExpirydate(Coupon coupon, CouponClassExpireStrategy record) {
		//绝对有效期
		if (Check.eq(record.getExpiryStrategy(), CouponClassExpiryStrategy.ABSOLUTE_EXPIRY)) {
			coupon.setStartEffectiveTime(record.getAbsoluteStartTime());
			coupon.setEndEffectiveTime(record.getAbsoluteEndTime());
		} else {
			//相对有效期
			Calendar calendar = Calendar.getInstance();
			if (Check.eq(record.getRelativeExpiryType(), CouponClassRelativeExpiryType.YEAR.real())) {
				calendar.add(Calendar.YEAR, record.getRelativeExpiryValue());
			} else if (Check.eq(record.getRelativeExpiryType(), CouponClassRelativeExpiryType.MONTH.real())) {
				calendar.add(Calendar.MONTH, record.getRelativeExpiryValue());
			} else if (Check.eq(record.getRelativeExpiryType(), CouponClassRelativeExpiryType.DAY.real())) {
				calendar.add(Calendar.DAY_OF_MONTH, record.getRelativeExpiryValue());
			}
			// setting time
			DateUtil.setMaxTimePart(calendar);
			Calendar end = Calendar.getInstance();
			DateUtil.cleanTimePart(end);
			coupon.setStartEffectiveTime(end.getTime());
			coupon.setEndEffectiveTime(calendar.getTime());
		}

	}
}